﻿using System;
using System.Collections.ObjectModel;
using System.Windows.Controls;
using Microsoft.Practices.Composite.Events;
using StockholmsStad.Windows.UI.Modules.Ceremony.Events;
using StockholmsStad.Windows.UI.Modules.Ceremony.Interfaces;
using StockholmsStad.Windows.UI.Modules.Ceremony.Models;
using StockholmsStad.Runtime.Serialization.DataContract.Enums;
using StockholmsStad.Runtime.Serialization.DataContract;
using System.Collections.Generic;
using Microsoft.Practices.Composite.Presentation.Events;

namespace StockholmsStad.Windows.UI.Modules.Ceremony.Views
{
    /// <summary>
    /// Interaction logic for CeremonyListView.xaml
    /// </summary>
    public partial class CeremonyListView : ICeremonyListView
    {
        readonly ICeremonyService ceremonyService;
        private readonly SubscriptionToken subscriptionToken;
        private readonly IEventAggregator eventAggregator;
        private bool updateTicketHandled;

        public CeremonyListView(ICeremonyService service, IEventAggregator aggregator)
        {
            InitializeComponent();

            eventAggregator = aggregator;
            ceremonyService = service;

            var updateTicketsWithStatusEvent = eventAggregator.GetEvent<UpdateTicketsWithStatus>();

            if (subscriptionToken != null)
            {
                updateTicketsWithStatusEvent.Unsubscribe(subscriptionToken);
            }

            subscriptionToken = updateTicketsWithStatusEvent.Subscribe(UpdateTicketsWithStatusHandler, ThreadOption.UIThread, false);

            Loaded += CeremonyListView_Loaded;
            btnSearch.Click += btnSearch_Click;

            rbListCeremonyTypes.LayoutUpdated += rbListCeremonyTypes_LayoutUpdated;
            listViewIndividualCeremony.Visibility = System.Windows.Visibility.Collapsed;
            ceremonyService.GetOrdinaryCeremoniesCompleted += service_GetOrdinaryCeremoniesCompleted;
        }

        private void UpdateTicketsWithStatusHandler(ObservableCollection<CeremonyDetailsPresentationModel> models)
        {
            //if (!updateTicketHandled)
            //{
                updateTicketHandled = true;
                ceremonyService.UpdateTicketsWithStatus(models);
            //}
        }

        #region ICeremonyListView Members

        public event EventHandler<DataEventArgs<CeremonySummaryPresentationModel>> CeremonySelected = delegate { };

        private List<TimeBlock> freeTimeBlocks;
        public List<TimeBlock> FreeTimeBlocks
        {
            get
            {
                return freeTimeBlocks;
            }
            set
            {
                freeTimeBlocks = value;
                lvFreeTimes.DataContext = freeTimeBlocks;
            }
        }

        private ObservableCollection<CeremonySummaryPresentationModel> model;
        public ObservableCollection<CeremonySummaryPresentationModel> Model
        {
            get { return model; }
            set
            {
                model = value;

                ValueIdPair ceremonyType = (ValueIdPair) rbListCeremonyTypes.SelectedItem ??
                                           new ValueIdPair
                                               {
                                                   Id = (int) CeremonyType.Ordinary,
                                                   Name = Enum.GetName(typeof (CeremonyType), CeremonyType.Ordinary)
                                               };

                listViewOrdinaryCeremony.DataContext = ceremonyType.Id == (int) CeremonyType.Ordinary ? value : null;
                listViewIndividualCeremony.DataContext = ceremonyType.Id == (int) CeremonyType.Individual
                                                             ? value
                                                             : null;

                listViewOrdinaryCeremony.Visibility = listViewOrdinaryCeremony.DataContext == null
                                                          ? System.Windows.Visibility.Collapsed
                                                          : System.Windows.Visibility.Visible;
                listViewIndividualCeremony.Visibility = listViewIndividualCeremony.DataContext == null
                                                            ? System.Windows.Visibility.Collapsed
                                                            : System.Windows.Visibility.Visible;
            }
        }

        #endregion

        void CeremonyListView_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {            
            List<Minister> ministers = ceremonyService.GetMinisters();
            cbMinister.DataContext = ministers;

            List<ValueIdPair> ceremonyTypes = ceremonyService.GetCeremonyTypes();
            rbListCeremonyTypes.DataContext = ceremonyTypes;
            Model = ceremonyService.GetOrdinaryCeremonies();

            lvFreeTimes.DataContext = new List<TimeBlock>();
            //ceremonyService.GetOrdinaryCeremoniesASync();
        }

        void rbListCeremonyTypes_LayoutUpdated(object sender, EventArgs e)
        {
            if (rbListCeremonyTypes.SelectedItem == null && rbListCeremonyTypes.Items.Count > 0)
            {
                rbListCeremonyTypes.SelectedIndex = 0;
            }
        }

        void btnSearch_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Search();
        }

        private void listviewCeremony_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                var selected = e.AddedItems[0] as CeremonySummaryPresentationModel;
                if (selected != null)
                {
                    CeremonySelected(this, new DataEventArgs<CeremonySummaryPresentationModel>(selected));
                }
            }
        }

        private void Search()
        {

            // CermonyType            
            if (rbListCeremonyTypes.SelectedItem == null)
                rbListCeremonyTypes.SelectedIndex = 0;

            var ceremonyType = (ValueIdPair) rbListCeremonyTypes.SelectedItem;
            if (ceremonyType == null)
                ceremonyType = new ValueIdPair()
                                   {
                                       Id = 1,
                                       Name = "Ordinary"
                                   };

            // DO SEARCH
            DateTime? dateFrom = dtpDateFrom.SelectedDate;
            DateTime? dateTo = dtpDateTo.SelectedDate;
            Minister minister = cbMinister.SelectedIndex >= 0 ? cbMinister.SelectedItem as Minister : null;
            int? ministerId = minister != null ? minister.MinisterId : null;
            DateTime? toDate = null;

            if (dateTo.HasValue)
                toDate = dateTo.Value;

            if ((int) CeremonyType.Individual == ceremonyType.Id)
            {
                if (dateFrom.HasValue)
                {
                    Model = ceremonyService.GetIndividualCeremonies(dateFrom.Value, toDate, ministerId);
                }
                else
                {
                    if (dateTo.HasValue || ministerId != null)
                    {
                        var fromDate = ceremonyService.GetPreviousCeremonyDateForIndividualService();
                        Model = ceremonyService.GetIndividualCeremonies(fromDate, dateTo, ministerId);
                    }
                    else
                    {
                        Model = ceremonyService.GetIndividualCeremonies();
                    }
                }
            }
            else
            {
                if (dateFrom.HasValue)
                {
                    Model = ceremonyService.GetOrdinaryCeremonies(dateFrom.Value, dateTo, ministerId);
                    //ceremonyService.GetOrdinaryCeremoniesASync(dateFrom.Value, dateTo, ministerId);
                }
                else
                {
                    if (dateTo.HasValue || ministerId != null)
                    {
                        var fromDate = ceremonyService.GetPreviousCeremonyDateForOrdinaryService();
                        Model = ceremonyService.GetOrdinaryCeremonies(fromDate, dateTo, ministerId);
                    }
                    else
                    {
                        Model = ceremonyService.GetOrdinaryCeremonies();
                    }
                    
                }
            }

            // återställ checkboxen för förrättare
            cbMinister.SelectedIndex = -1;
        }

        void service_GetOrdinaryCeremoniesCompleted(object sender, CeremonySummaryPresentationModelEventArgs e)
        {
            Model = e.Data;
        }
    }
}
